package service

import (
	"fmt"
	"gorm.io/gorm"
	common "monitor_serve/commons/jwt"
	"monitor_serve/initialize"
	"monitor_serve/model"
	"monitor_serve/util"
	"time"
)

type UserService struct {
}

var pwdSalt = "m#190*"

// UserSignUp 用户注册
func (u *UserService) UserSignUp(username, password string) error {
	// 1. 判断用户名是否存在
	var user model.User
	if err := initialize.DB.Where("username = ?", username).First(&user).Error; err == nil {
		return fmt.Errorf("username already exists")
	}

	// 2. 将密码进行加密
	encryptedPassword := util.Sha1([]byte(password + pwdSalt))

	// 3. 保存进数据库
	newUser := model.User{
		Username:   username,
		Password:   encryptedPassword,
		SignupAt:   time.Now(),
		LastActive: time.Now(),
	}
	if err := initialize.DB.Create(&newUser).Error; err != nil {
		return err
	}

	return nil
}

// UserSignIn 用户登录
func (u *UserService) UserSignIn(username, password string) (string, error) {
	// 1. 查询用户
	var user model.User
	if err := initialize.DB.Where("username = ?", username).First(&user).Error; err != nil {
		return "", fmt.Errorf("username not exists")
	}

	// 2. 验证密码
	encryptedPassword := util.Sha1([]byte(password + pwdSalt))
	if encryptedPassword != user.Password {
		return "", fmt.Errorf("password error")
	}

	// 3. 生成token
	token, err := common.GenerateToken(username)
	if err != nil {
		return "", err
	}
	err = ServiceGroupApp.UserTokenService.UserTokenSave(username, token)
	if err != nil {
		return "", err
	}
	// 4. 更新最后登录时间
	if err := initialize.DB.Model(&user).Update("last_active", time.Now()).Error; err != nil {
		return "", err
	}

	return token, nil
}

// 获取用户信息
func (u *UserService) GetUserInfo(username string) (*model.User, error) {
	var user model.User
	result := initialize.DB.Where("username = ?", username).First(&user)
	if result.Error != nil {
		// 如果查询出错（非记录未找到错误），返回错误
		if result.Error != gorm.ErrRecordNotFound {
			return nil, result.Error
		}
		// 如果记录未找到，返回 nil 表示没有找到用户
		return nil, fmt.Errorf("user not found")
	}
	return &user, nil
}
